package com.takeshequ.publish;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.takeshequ.BasicActivity;
import com.takeshequ.Constants;
import com.takeshequ.R;
import com.takeshequ.main.MainFragmentActivity;

public class PublishActivity extends BasicActivity {
	private SelectPicPopupWindow menuWindow;
	private final int CASE_CAMERA = 1;
	@ViewInject(id = R.id.publish_content)
	private EditText publishContent;
	@ViewInject(id = R.id.publish_camera_btn, click = "clickCamera")
	private ImageView cameraBtn;

	@ViewInject(id = R.id.publish_photo_btn, click = "clickPhoto")
	private ImageView photoBtn;
	@ViewInject(id = R.id.publish_face_btn, click = "createExpressionDialog")
	private ImageView faceBtn;
	
	@ViewInject(id = R.id.publish_back, click = "back")
	private Button back;

	@ViewInject(id = R.id.publish_photo_pre_view)
	private ImageView cameraPreView;
	@ViewInject(id = R.id.publish_photo_pre_view_layout)
	private View cameraPreViewLayout;

	@ViewInject(id = R.id.publish_place_text)
	private TextView placeText;

	@ViewInject(id = R.id.publish_place_btn, click = "clickPlaceBtn")
	private ImageView placeBtn;
	@ViewInject(id = R.id.publish_place_view)
	private View placeView;

	@ViewInject(id = R.id.publish_send_btn, click = "send")
	private ImageButton sendBtn;

	private Bitmap photoBitmap;

	private int choose;
	private int[] imageIds = new int[107];
	private Dialog builder;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.publish);
		Intent intent = getIntent();
		choose = intent.getIntExtra("choose", 1);
	}

	@Override
	protected void onResume() {
		super.onResume();
		switch (choose) {
		case 1:
			focusEditText();
			break;
		case 2:
			menuWindow = new SelectPicPopupWindow(PublishActivity.this,
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							menuWindow.dismiss();
							switch (v.getId()) {
							case R.id.btn_take_photo:
								clickCamera(v);
								break;
							case R.id.btn_pick_photo:
								clickPhoto(v);
								break;
							default:
								break;
							}

						}
					});
			popupHandler.sendEmptyMessageDelayed(0, 1000);

			break;
		case 3:
			clickPlaceBtn(null);
			focusEditText();
			break;
		case 4:
			createExpressionDialog(null);
			focusEditText();
			break;
		default:
			break;
		}

	};

	/**
	 * 创建一个表情选择对话框
	 */
	public void createExpressionDialog(View view) {
		builder = new Dialog(PublishActivity.this);
		GridView gridView = createGridView();
		builder.setContentView(gridView);
		builder.setTitle("默认表情");
		builder.show();
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Bitmap bitmap = null;
				bitmap = BitmapFactory.decodeResource(getResources(),
						imageIds[arg2 % imageIds.length]);
				ImageSpan imageSpan = new ImageSpan(PublishActivity.this, bitmap);
				String str = null;
				if (arg2 < 10) {
					str = "f00" + arg2;
				} else if (arg2 < 100) {
					str = "f0" + arg2;
				} else {
					str = "f" + arg2;
				}
				SpannableString spannableString = new SpannableString(str);
				spannableString.setSpan(imageSpan, 0, 4,
						Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				publishContent.append(spannableString);
				builder.dismiss();
				focusEditText();
			}
		});
	}

	/**
	 * 生成一个表情对话框中的gridview
	 * 
	 * @return
	 */
	private GridView createGridView() {
		final GridView view = new GridView(this);
		List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
		// 生成107个表情的id，封装
		for (int i = 0; i < 107; i++) {
			try {
				if (i < 10) {
					Field field = R.drawable.class.getDeclaredField("f00" + i);
					int resourceId = Integer.parseInt(field.get(null)
							.toString());
					imageIds[i] = resourceId;
				} else if (i < 100) {
					Field field = R.drawable.class.getDeclaredField("f0" + i);
					int resourceId = Integer.parseInt(field.get(null)
							.toString());
					imageIds[i] = resourceId;
				} else {
					Field field = R.drawable.class.getDeclaredField("f" + i);
					int resourceId = Integer.parseInt(field.get(null)
							.toString());
					imageIds[i] = resourceId;
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
			Map<String, Object> listItem = new HashMap<String, Object>();
			listItem.put("image", imageIds[i]);
			listItems.add(listItem);
		}

		SimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems,
				R.layout.team_layout_single_expression_cell,
				new String[] { "image" }, new int[] { R.id.image });
		view.setAdapter(simpleAdapter);
		view.setNumColumns(6);
		view.setBackgroundColor(Color.rgb(214, 211, 214));
		view.setHorizontalSpacing(1);
		view.setVerticalSpacing(1);
		view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT));
		view.setGravity(Gravity.CENTER);
		return view;
	}

	private void focusEditText() {
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {

			public void run() {
				InputMethodManager inputManager = (InputMethodManager) publishContent
						.getContext().getSystemService(
								Context.INPUT_METHOD_SERVICE);
				inputManager.showSoftInput(publishContent, 0);
			}

		}, 998);
	}

	private Handler popupHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				menuWindow.showAtLocation(
						PublishActivity.this.findViewById(R.id.publish_main),
						Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
				menuWindow.update();
				break;
			}
		}

	};

	public void clickCamera(View view) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(intent, CASE_CAMERA);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		try {
			if (resultCode == Activity.RESULT_OK) {
				choose = 1;
				if (requestCode == CASE_CAMERA) {
					// FinalBitmap.create(this).display(cameraPreView,
					// strPath,cameraPreView.getWidth(),cameraPreView.getHeight());
					Bundle extras = data.getExtras();
					photoBitmap = (Bitmap) extras.get("data");
					cameraPreView.setImageBitmap(Bitmap.createScaledBitmap(
							photoBitmap, 200, 130, true));
					cameraPreViewLayout.setVisibility(View.VISIBLE);
				} else if (requestCode == IMAGE_CODE) {
					ContentResolver resolver = getContentResolver();
					Uri originalUri = data.getData();
					photoBitmap = MediaStore.Images.Media.getBitmap(resolver,
							originalUri);
					cameraPreView.setImageBitmap(Bitmap.createScaledBitmap(
							photoBitmap, 200, 130, true));
					cameraPreViewLayout.setVisibility(View.VISIBLE);
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void clickPlaceBtn(View view) {
		String address = Constants.address;
		placeText.setText(address);
		placeView.setVisibility(View.VISIBLE);
	}

	private final String IMAGE_TYPE = "image/*";

	private final int IMAGE_CODE = 0; // 这里的IMAGE_CODE是自己任意定义的

	public void clickPhoto(View view) {
		Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
		getAlbum.setType(IMAGE_TYPE);
		startActivityForResult(getAlbum, IMAGE_CODE);
	}

	public void back(View v) {
		overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
		startActivity(new Intent(PublishActivity.this,
				MainFragmentActivity.class));
	}

	public void hidePlaceView(View view) {
		view.setVisibility(View.GONE);
	}

	public void hidePhotoView(View view) {
		cameraPreViewLayout.setVisibility(View.GONE);
	}

	public void send(View view) {
		AjaxParams params = new AjaxParams();
		params.put("appSource", "A");
		params.put("appVersion", "1");
		params.put("regSource", "mobile");
		params.put("cont", publishContent.getText().toString());
		params.put("memberId", Constants.memberId);
		params.put("nickName", Constants.member.getNickName());
		params.put("headImage", Constants.member.getHeadImage());
		if (cameraPreViewLayout.getVisibility() == View.VISIBLE) {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
			params.put("filename", new ByteArrayInputStream(baos.toByteArray())); // 提交字节流
		}
		if (placeView.getVisibility() == View.VISIBLE) {
			params.put("gpsLatitude", Constants.latitude);
			params.put("gpsLongitude", Constants.longitude);
		}
		FinalHttp fh = new FinalHttp();
		 fh.configTimeout(60000);
		fh.post(Constants.domainAndPort+"/submitDiary", params,
				new AjaxCallBack<String>() {
					private ProgressDialog dialog;

					@Override
					public void onLoading(long count, long current) {
//						System.out.println(current + "/" + count);
//						dialog.setMessage("正在发布,请稍候...(" + current + "/"
//								+ count + ")");
					}

					@Override
					public void onStart() {
						dialog = ProgressDialog.show(PublishActivity.this, "",
								"正在发布,请稍候...", true);
					}

					@Override
					public void onFailure(Throwable t, String strMsg) {
						dialog.dismiss();
					}

					@Override
					public void onSuccess(String t) {
						System.out.println(t);
						dialog.dismiss();
						back(null);
					}

				});

	}
}
